package com.github.slprj.slake.net;

import com.github.slprj.slake.pb.PbCallback;
import com.github.slprj.slake.pb.PbException;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @author YangXiaoLong
 * 2022/8/23 8:59
 */
public class RpcPbCallback implements PbCallback {
    private Frame frame;
    private int bodyStart;
    private int bodyLimit;

    public RpcPbCallback() {
    }

    public void setFrame(Frame frame) {
        this.frame = frame;
    }

    @Override
    public void readInt(int index, int value) {
        switch (index) {
            case Frame.IDX_TYPE: {
                frame.setFrameType(value);
                break;
            }
            case Frame.IDX_COMMAND: {
                frame.setCommand(value);
                break;
            }
            case Frame.IDX_SEQ: {
                frame.setSeq(value);
                break;
            }
            case Frame.IDX_RESP_CODE: {
                frame.setRespCode(value);
                break;
            }
            default:
                throw new PbException("readInt" + index);
        }
    }

    @Override
    public void readLong(int index, long value) {

    }

    @Override
    public void readBytes(int index, ByteBuffer buf) {
        switch (index) {
            case Frame.IDX_MSG: {
                byte[] bs = new byte[buf.remaining()];
                buf.get(bs);
                frame.setMsg(new String(bs, StandardCharsets.UTF_8));
                break;
            }
            case Frame.IDX_BODY: {
                bodyStart = buf.position();
                bodyLimit = bodyStart + buf.remaining();
                break;
            }
            default: {
                //todo dongting 有错误
                throw new PbException("readBytes" + index);
            }
        }
    }

    public int getBodyStart() {
        return bodyStart;
    }

    public int getBodyLimit() {
        return bodyLimit;
    }
}
